#include "angelscript_function_extension.hpp"
#include "angelscript.h"
#include "angelscript_base.hpp"
#include "scripting/scripting_api.h"
#include "scripting/scripting_module.h"

#include <cassert>

IScript* AngelScriptFunctionExtension::create(std::string title, std::string_view code, const std::string &script_path)
{
    AngelScriptFunctionExtension *e = new AngelScriptFunctionExtension(std::move(title), script_path);
    if (!e->compile(code)) {
        delete e;
        e = nullptr;
    }

    return e;
}

bool AngelScriptFunctionExtension::compile(const std::string_view &code)
{
    auto engine = AngelScriptShared::GetEngine();
    auto module = engine->GetModule(module_name.c_str(), asGM_ALWAYS_CREATE); // 这里始终要创建模块
    module->AddScriptSection("Main", code.data());
    if (module->Build() < 0)
    {
        return false;
    }
    return true;
}


void AngelScriptFunctionExtension::execute()
{
    auto engine = AngelScriptShared::GetEngine();
    auto module = engine->GetModule(module_name.c_str(), asGM_ONLY_IF_EXISTS); // 这里始终要创建模块
    assert (module != nullptr && "Module missing?");

    auto ctx = engine->CreateContext();
    
    ctx->Prepare(module->GetFunctionByDecl("void main()"));
    ctx->Execute();
    ctx->Release();
}

AngelScriptFunctionExtension::AngelScriptFunctionExtension(std::string title, const std::string &script_path):
    IFunctionalScript(std::move(title), script_path, g_current_module),
    AngelScriptBase(script_path, "Function")
{
    
}

AngelScriptFunctionExtension::~AngelScriptFunctionExtension()
{
    
}
